<?php

class Poll_Api_Poll extends Core_Api_Abstract
{
	public function getPollsPaginator($params = array())
	{
		 
		$paginator = Zend_Paginator::factory($this->getPollsSelect($params));
		if( !empty($params['page']) )
		{
			$paginator->setCurrentPageNumber($params['page']);
		}
		if( !empty($params['limit']) )
		{
			$paginator->setItemCountPerPage($params['limit']);
		}

		if( empty($params['limit']) )
		{
			$page = (int) Engine_Api::_()->getApi('settings', 'core')->getSetting('poll.product.pagenumber', 10);
			$paginator->setItemCountPerPage($page);
		}
		
		

		return $paginator;
	}

	/**
	 * Gets a select object for the user's blog entries
	 *
	 * @param Core_Model_Item_Abstract $user The user to get the messages for
	 * @return Zend_Db_Table_Select
	 */
	public function getPollsSelect($params = array())
	{		 
		$table = Engine_Api::_()->getDbtable('polls', 'poll');
		$select = $table->select();
        
		if(isset($params["user_id"])) $select=$select->where("user_id= ? ", $params["user_id"]);
        if (!empty($params['title'])) $select->where("`title` LIKE '%{$params["title"]}%'");
        if (!empty($params['owner'])) {
            $select->setIntegrityCheck(false)
                ->from(array('q' => $table->info('name')))
                ->join(array('u' => 'engine4_users'), 'q.user_id = u.user_id', NULL)
                ->where("u.username LIKE '%{$params['owner']}%' OR u.displayname LIKE '%{$params['owner']}%' OR u.email LIKE '%{$params['owner']}%'");
        }
        if (isset($params['feature']) && $params['feature'] != -1) {
            $select->where('feature = ?', $params['feature']);
        }
        if (!empty($params['privacy'])) {
            $select->where('privacy = ?', $params['privacy']);
        }
		
		if(isset($params['order'])) $select->order($params['order'].' '.$params['order_direction']); 
        $select->order('creation_date DESC'); 
        
		return $select;
	}

	public  static function getAllAddress($poll_id,$fecth)
	{
		$tablecontactaddress=Engine_Api::_()->getDbTable("contactaddresses","poll");
		$select=$tablecontactaddress->select()
		->where("contactaddress_poll_id = ?",$poll_id);
		$rows=$tablecontactaddress->getAdapter()->fetchAll($select);

			
		$tableAddress=Engine_Api::_()->getDbtable("addresses","poll");
		$where=null;
		foreach ($rows as $row) {
			$where=$where." address_id= '".$row['contactaddress_id']."' or ";
		}
		$where=$where."1=2";

		$addressselect=$tableAddress->select()
		->where($where);
			
		if($fecth==false) return $addressselect;

		$rowaddress=$tableAddress->fetchAll($addressselect);
		return $rowaddress;
		 
	}

	public  function getPollInfo($poll_id)
    {
    	$pollTable=Engine_Api::_()->getDbtable('polls','poll');
    	$select=$pollTable->select()
    						->where('poll_id=?',$poll_id);
    	$row=$pollTable->fetchRow($select);
    	return  $row;
    }

/* returns an array of [days],[hours],[minutes],[seconds] time left from now to timestamp given */
    public function timeLeft($time_left=0, $endtime=null) {
        if($endtime != null)
            $time_left = $endtime - time();
        if($time_left > 0) {
            $days = floor($time_left / 86400);
            $time_left = $time_left - $days * 86400;
            $hours = floor($time_left / 3600);
            $time_left = $time_left - $hours * 3600;
            $minutes = floor($time_left / 60);
            $seconds = $time_left - $minutes * 60;
        } else {
            return array('days'=>0, 'hours'=> 0,'mins'=> 0);//,'seconds'=> 0);
        }
        return array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes);//, 'seconds'=>$seconds);
    }
    
    //PARSE KEY
	
    public function statisticPoll($date) {
    
    	$pollTable=Engine_Api::_()->getDbtable('polls','poll');
    	$select=$pollTable->select();
    	$select = $select->where("DATE_FORMAT(creation_date,'%Y') = ?",date('Y',  strtotime($date)));
    	
    	$rows = $pollTable->fetchAll($select);
    	
    	$today = array(
    		'OnEditing' => 0,
    		'WaitingApprove' => 0,
    		'BestApprove' => 0,
    		'ReadyToRun' => 0,
    		'Running' => 0,
    		'Completed' => 0,
    		'Fail' => 0,
    		'Canceled' => 0
    	);
    	$thisWeek = array(
    		'OnEditing' => 0,
    		'WaitingApprove' => 0,
    		'BestApprove' => 0,
    		'ReadyToRun' => 0,
    		'Running' => 0,
    		'Completed' => 0,
    		'Fail' => 0,
    		'Canceled' => 0
    	);
    	$thisMonth = array(
    		'OnEditing' => 0,
    		'WaitingApprove' => 0,
    		'BestApprove' => 0,
    		'ReadyToRun' => 0,
    		'Running' => 0,
    		'Completed' => 0,
    		'Fail' => 0,
    		'Canceled' => 0
    	);
    	$thisYear = array(
    		'OnEditing' => 0,
    		'WaitingApprove' => 0,
    		'BestApprove' => 0,
    		'ReadyToRun' => 0,
    		'Running' => 0,
    		'Completed' => 0,
    		'Fail' => 0,
    		'Canceled' => 0
    	);
    	
    	
    	
    	$lstResult = array('toDay'=> $today,'thisWeek'=>$thisWeek,'thisMonth'=>$thisMonth ,'thisYear'=>$thisYear);
    	if(count($rows) <=0 ) return $lstResult;
    	foreach ($rows as $value) {
    		if($value->status == Poll_Model_Poll::STATUS_ON_EDITTING){
    			$thisYear['OnEditing'] += 1;
    			if(date('m',strtotime($value->creation_date))== date('m',strtotime($date))){
    				$thisMonth['OnEditing'] += 1;
    				
	    			if(date('L',strtotime($value->creation_date))== date('L',strtotime($date))){
	    				$thisWeek['OnEditing'] += 1;
	    				
		    			if(date('d',strtotime($value->creation_date))== date('d',strtotime($date))){
		    				$today['OnEditing'] += 1;
		    			}
	    			}
    			}
    			
    			continue;
    		}
    		if($value->status == Poll_Model_Poll::STATUS_WAITING_APPROVE){
    			$thisYear['WaitingApprove'] += 1;
    			
	    		if(date('m',strtotime($value->creation_date))== date('m',strtotime($date))){
	    				$thisMonth['WaitingApprove'] += 1;
	    				
		    			if(date('L',strtotime($value->creation_date))== date('L',strtotime($date))){
		    				$thisWeek['WaitingApprove'] += 1;
		    				
			    			if(date('d',strtotime($value->creation_date))== date('d',strtotime($date))){
			    				$today['WaitingApprove'] += 1;
			    			}
		    			}
	    		}
    			continue;
    		}
    		if($value->status == Poll_Model_Poll::STATUS_READY_TO_RUN){
    			$thisYear['ReadyToRun'] += 1;
    			
    			if(date('m',strtotime($value->creation_date))== date('m',strtotime($date))){
	    				$thisMonth['ReadyToRun'] += 1;
	    				
		    			if(date('L',strtotime($value->creation_date))== date('L',strtotime($date))){
		    				$thisWeek['ReadyToRun'] += 1;
		    				
			    			if(date('d',strtotime($value->creation_date))== date('d',strtotime($date))){
			    				$today['ReadyToRun'] += 1;
			    			}
		    			}
	    			}
    			continue;
    		}
    		if($value->status == Poll_Model_Poll::STATUS_BEST_APPROVE){
    			$thisYear['BestApprove'] += 1;
    			
    			if(date('m',strtotime($value->creation_date))== date('m',strtotime($date))){
	    				$thisMonth['BestApprove'] += 1;
	    				
		    			if(date('L',strtotime($value->creation_date))== date('L',strtotime($date))){
		    				$thisWeek['BestApprove'] += 1;
		    				
			    			if(date('d',strtotime($value->creation_date))== date('d',strtotime($date))){
			    				$today['BestApprove'] += 1;
			    			}
		    			}
	    			}
    			continue;
    		}
    		if($value->status == Poll_Model_Poll::STATUS_RUNNING){
    			$thisYear['Running'] += 1;
    			
    			if(date('m',strtotime($value->creation_date))== date('m',strtotime($date))){
	    				$thisMonth['Running'] += 1;
	    				
		    			if(date('L',strtotime($value->creation_date))== date('L',strtotime($date))){
		    				$thisWeek['Running'] += 1;
		    				
			    			if(date('d',strtotime($value->creation_date))== date('d',strtotime($date))){
			    				$today['Running'] += 1;
			    			}
		    			}
	    			}
    			continue;
    		}
    		if($value->status == Poll_Model_Poll::STATUS_FAILED){
    			$thisYear['Fail'] += 1;
    			
    			if(date('m',strtotime($value->creation_date))== date('m',strtotime($date))){
	    				$thisMonth['Fail'] += 1;
	    				
		    			if(date('L',strtotime($value->creation_date))== date('L',strtotime($date))){
		    				$thisWeek['Fail'] += 1;
		    				
			    			if(date('d',strtotime($value->creation_date))== date('d',strtotime($date))){
			    				$today['Fail'] += 1;
			    			}
		    			}
	    			}
    			continue;
    		}
    		if($value->status == Poll_Model_Poll::STATUS_COMPLETE){
    			$thisYear['Completed'] += 1;
    			
    			if(date('m',strtotime($value->creation_date))== date('m',strtotime($date))){
	    				$thisMonth['Completed'] += 1;
	    				
		    			if(date('L',strtotime($value->creation_date))== date('L',strtotime($date))){
		    				$thisWeek['Completed'] += 1;
		    				
			    			if(date('d',strtotime($value->creation_date))== date('d',strtotime($date))){
			    				$today['Completed'] += 1;
			    			}
		    			}
	    			}
    			continue;
    		}
    		if($value->status == Poll_Model_Poll::STATUS_CANCELLED){
    			$thisYear['Canceled'] += 1;
    			
    			if(date('m',strtotime($value->creation_date))== date('m',strtotime($date))){
	    				$thisMonth['Canceled'] += 1;
	    				
		    			if(date('L',strtotime($value->creation_date))== date('L',strtotime($date))){
		    				$thisWeek['Canceled'] += 1;
		    				
			    			if(date('d',strtotime($value->creation_date))== date('d',strtotime($date))){
			    				$today['Canceled'] += 1;
			    			}
		    			}
	    			}
    			continue;
    		}
			if($value->status == Poll_Model_Poll::STATUS_APPROVED){
    			$thisYear['Approved'] += 1;
    			
    			if(date('m',strtotime($value->creation_date))== date('m',strtotime($date))){
	    				$thisMonth['Approved'] += 1;
	    				
		    			if(date('L',strtotime($value->creation_date))== date('L',strtotime($date))){
		    				$thisWeek['Approved'] += 1;
		    				
			    			if(date('d',strtotime($value->creation_date))== date('d',strtotime($date))){
			    				$today['Approved'] += 1;
			    			}
		    			}
	    			}
    			continue;
    		}
    		
    	}
    	$lstResult = array('toDay'=> $today,'thisWeek'=>$thisWeek,'thisMonth'=>$thisMonth ,'thisYear'=>$thisYear);
    	return 	 $lstResult;				
    }
    
    
    private function initArrayQuestionStatus(){
    	$today = array(
    		'OnEditing' => 0,
    		'WaitingApprove' => 0,
    		'BestApprove' => 0,
    		'ReadyToRun' => 0,
    		'Running' => 0,
    		'Completed' => 0,
    		'Fail' => 0,
    		'Canceled' => 0
    	);
    }
    
	
    public function statisticBid($date){
    	$historyTable=Engine_Api::_()->getDbtable('biders','question');
    	$select=$historyTable->select();
    	$select = $select->where("DATE_FORMAT(bought_date,'%Y') = ?",date('Y',  strtotime($date)));
    	$select= $select->where("type = 'bid'" );
    	$rows = $historyTable->fetchAll($select);
    	if(count($rows)<=0 ) return array('toDay'=> 0,'thisWeek' => 0, 'thisMonth'=>0,'thisYear'=>0);
    	
    	$thisYear = 0;
    	$thisMonth = 0;
    	$thisWeek = 0;
    	$toDay = 0;
    	foreach ($rows as $value) {
    		$thisYear +=$value->price;
    		if(date('m',strtotime($value->bought_date))== date('m',strtotime($date))){
	    		$thisMonth += $value->price;
	    				
		    	if(date('L',strtotime($value->bought_date))== date('L',strtotime($date))){
		    		$thisWeek += $value->price;
		    				
			    	if(date('d',strtotime($value->bought_date))== date('d',strtotime($date))){
			    		$toDay += $value->price;
			    	}
		    	}
	    	}
    	}
    	return array('toDay'=> $toDay,'thisWeek' => $thisWeek, 'thisMonth'=>$thisMonth,'thisYear'=>$thisYear);
    	
    }
    public  function statisticFee($date){
    	
    	$runStatus = Question_Model_Question::STATUS_RUNNING;
    	$bestStatus =  Question_Model_Question::STATUS_BEST_APPROVE;
    	$bestStatus = Question_Model_Question::STATUS_COMPLETE;
    	$currentStatus = false;
    	
    	$historyTable=Engine_Api::_()->getDbtable('questions','question');
    	$select=$historyTable->select();
    	$select = $select->where("DATE_FORMAT(modified_date,'%Y') = ?",date('Y',  strtotime($date)));
    	$select= $select->where("status =  $runStatus or status = $bestStatus ");
    	$rows = $historyTable->fetchAll($select);	
    	if(count($rows)<=0 ) return array('toDay'=> 0,'thisWeek' => 0, 'thisMonth'=>0,'thisYear'=>0);
    	
    	$thisYear = 0;
    	$thisMonth = 0;
    	$thisWeek = 0;
    	$toDay = 0;
    	foreach ($rows as $value) {
    		$currentStatus = false;
    		if($value->status==Question_Model_Question::STATUS_COMPLETE) $currentStatus = true;
    		$thisYear +=$value->getAllFee($currentStatus);
    		if(date('m',strtotime($value->modified_date))== date('m',strtotime($date))){
	    		$thisMonth += $value->getAllFee($currentStatus);
	    				
		    	if(date('L',strtotime($value->modified_date))== date('L',strtotime($date))){
		    		$thisWeek += $value->getAllFee($currentStatus);
		    				
			    	if(date('d',strtotime($value->modified_date))== date('d',strtotime($date))){
			    		$toDay += $value->getAllFee($currentStatus);
			    	}
		    	}
	    	}
    	}
    	return array('toDay'=> $toDay,'thisWeek' => $thisWeek, 'thisMonth'=>$thisMonth,'thisYear'=>$thisYear);
    	
    }
    public  function statisticRefund($date,$type = 0)
    {
    	$historyTable=Engine_Api::_()->getDbtable('historyrefunds','question');
    	$select=$historyTable->select();
    	$select = $select->where("DATE_FORMAT(refund_date,'%Y') = ?",date('Y',  strtotime($date)));
    	$select= $select->where("type = ?" ,$type);
    	
    	$rows = $historyTable->fetchAll($select);
    	
    	if(count($rows)<=0 ) return array('toDay'=> 0,'thisWeek' => 0, 'thisMonth'=>0,'thisYear'=>0);
    	
    	$thisYear = 0;
    	$thisMonth = 0;
    	$thisWeek = 0;
    	$toDay = 0;
    	foreach ($rows as $value) {
    		$thisYear +=$value->moneyrefund;
    		if(date('m',strtotime($value->refund_date))== date('m',strtotime($date))){
	    		$thisMonth += $value->moneyrefund;
	    				
		    	if(date('L',strtotime($value->refund_date))== date('L',strtotime($date))){
		    		$thisWeek += $value->moneyrefund;
		    				
			    	if(date('d',strtotime($value->refund_date))== date('d',strtotime($date))){
			    		$toDay += $value->moneyrefund;
			    	}
		    	}
	    	}
    	}
    	return array('toDay'=> $toDay,'thisWeek' => $thisWeek, 'thisMonth'=>$thisMonth,'thisYear'=>$thisYear);
    	
    }
    
    
}
